<template>
  <div class="auth-container">
    <el-card class="auth-card">
      <h2 class="text-center mb-6">用户登录</h2>
      <el-form
          ref="loginForm"
          :model="form"
          @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
              v-model="form.username"
              placeholder="请输入用户名"
              prefix-icon="User"
              clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              native-type="submit"
              class="w-full"
              :loading="loading"
          >
            登录
          </el-button>
        </el-form-item>

        <div class="text-center text-sm">
          <span class="text-gray-500">没有账号？</span>
          <el-link type="primary" @click="router.push('/register')">立即注册</el-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import {ref} from 'vue'
import axios from '@/utils/axios'
import router from "@/router/index";
import {useUserStore} from "@store/userStore.js";

const loading = ref(false);
const userStore = useUserStore()

const form = ref({
  username: '',
  password: ''
})

const handleLogin = async () => {
  loading.value = true;
  try {
    axios.post('/api/auth/login', form.value).then(data=>{
      data = data.data;
      userStore.setAuthData({
        username: data.username,
        role: data.role, // 根据后端返回设置角色
        token: data.token // 返回结构为 { data: 'jwt-token' }
      });
      // 跳转到登录前页面或首页
      const redirect = '/'
      router.push(redirect);
    })
  } catch (error) {
    // 错误处理已在axios拦截器处理
  } finally {
    loading.value = false;
  }
}
</script>

<style scoped>
.auth-container {
  @apply min-h-screen flex items-center justify-center bg-gray-100;
}

.auth-card {
  @apply w-96;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

:deep(.el-input__prefix) {
  @apply flex items-center px-2;
}
</style>